package com.yigerende.handler;


import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/*拦截所有的异常，进行统一的处理*/
@ControllerAdvice//拦截所有的注解控制器
public class ControllerExceptionHandler {

    /*导入这个包下面的Logger   import org.slf4j.Logger;*/
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    //返回的页面写个方法(处理异常信息)
    @ExceptionHandler(Exception.class)//这个方法可以处理异常信息
    public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
       //logger记录异常信息
        logger.error("Requst URL : {}，Exception : {}", request.getRequestURL(),e);

        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());//异常的url
        mv.addObject("exception", e);//获取到异常信息
        mv.setViewName("error/error");//返回自定义的error页面
        return mv;
    }
}
